package com.nuo.backend.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nuo.backend.common.exception.GlobalException;
import com.nuo.backend.config.LocalYml;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.UUID;

@Component
public class FileUtils {

    @Resource
    LocalYml localYml;


    private static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public R uploadToLocal(MultipartFile[] fileArr, String pathName) {
        JSONArray fileList = new JSONArray();
        Arrays.stream(fileArr).forEach(file -> {
            String originalFilename = file.getOriginalFilename();
            // 实例化json数据
            JSONObject jo = new JSONObject();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf('.'));
            String filePath = localYml.getUploadAddress() + "/" + pathName;
            try {
                uploadFile(file.getBytes(), filePath, fileName);
                jo.put("fileUrl", localYml.getVisitAddress() + pathName + "/" + fileName);
                jo.put("originalFilename", originalFilename);
                fileList.add(jo);
            } catch (Exception e) {
                throw new GlobalException("文件上传失败...");
            }
        });

        // 返回 json
        return R.ok("文件上传成功...").put("fileList" ,fileList);
    }
}
